#include <string.h>

#include "lib.h"

#include "growbuf.h"

#define GROWAMOUNT 256

char GrowBuf::empty = '\0';

GrowBuf::GrowBuf()
{
	maxSize = curSize = 0;
	buf = (char*)0;
}

GrowBuf::~GrowBuf()
{
	delete [] buf;
}



void
GrowBuf::clear()
{
	if (buf)
		delete [] buf;

	maxSize = curSize = 0;

	buf = (char*)0;
}


bool8
GrowBuf::add(char src)
{
	char str[2];

	str[0] = src;
	str[1] = 0;

	return add(str, strlen(str));
}


bool8
GrowBuf::add(char* src)
{
	return add(src, strlen(src));
}

bool8
GrowBuf::add(char* src, int32 amount)
{
	if (amount > 0)
	{
		if (curSize + amount >= maxSize && !ensure(curSize + amount))
			return false;

		memcpy(buf + curSize, src, amount);
		curSize += amount;
		buf[curSize] = '\0';
	}
	return true;
}

bool8
GrowBuf::ensure(int32 amt)
{
	// upon success, we *ALWAYS* have space for at least amt + 1 (for term null)
	//
	char* newBuf = new char[GROWAMOUNT + amt + 1];	// +1 for term null

	if (!newBuf)
		return false;	// current buf remains untouched

	if (curSize > 0)
		memcpy(newBuf, buf, curSize + 1);	// +1 for term null

	delete [] buf;
	buf = newBuf;
	maxSize = amt + GROWAMOUNT;		// do *NOT* add +1 for term null here!

	return true;
}
